package lt.web.controller.front;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;

import lt.web.pojo.*;
import lt.web.service.*;
import lt.web.utils.Constants;
import lt.web.utils.OssUtil;
import lt.web.utils.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/manager/dev")
public class DevUserController {

    @Autowired
    DevUserService devUserService;

    @Autowired
    AppInfoService appInfoService;

    @Autowired
    AppCategoryService appCategoryService;

    @Autowired
    DataDictionaryService dataDictionaryService;

    @Autowired
    AppVersionService appVersionService;


    //<editor-fold desc="首页展示模块">
    /**
     * APP 信息管理维护 查询
     * @param model
     * @param pageIndex
     * @return
     */
    @RequestMapping("/list")
    public String  backendAppList(Model model,HttpSession session,
                                  @RequestParam(defaultValue = "1") Integer pageIndex,
                                  @RequestParam(value = "querySoftwareName",required = false) String softwarename,
                                  @RequestParam(value = "queryStatus",required = false) Integer status,
                                  @RequestParam(value = "queryFlatformId",required = false) Integer flatFormId,
                                  @RequestParam(value = "queryCategoryLevel1",required = false) Integer categoryLevel1,
                                  @RequestParam(value = "queryCategoryLevel2",required = false)Integer categoryLevel2,
                                  @RequestParam(value = "queryCategoryLevel3",required = false)Integer categoryLevel3
    ) {

        Integer pageSize = Constants.pageSize;

        Integer totalCount = appInfoService.getAppInfoCount(softwarename, status, categoryLevel1, categoryLevel2, categoryLevel3, flatFormId, null);

        //分页功能
        PageSupport pageSupport = new PageSupport();

        //设置总数量
        pageSupport.setCurrentPageNo(pageIndex);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = pageSupport.getTotalPageCount();//总页数
        //控制首页和尾页
        if (pageIndex < 1) {
            pageIndex = 1;
        } else if (pageIndex > totalPageCount) {
            pageIndex = totalPageCount;
        }



       List<AppInfo> appInfoList = appInfoService.selectAllByCondation(softwarename, status, categoryLevel1, categoryLevel2, categoryLevel3,null,flatFormId,  pageIndex, pageSize);

        //一级分类列表
        List<AppCategory> categoryList1 = appCategoryService.getByCategorynameAppCategoryList(null);
        //获取平台列表
        List<DataDictionary> flatFormList = dataDictionaryService.getDataDictionaryList("APP_FLATFORM");
        //获取手游状态
        List<DataDictionary> appStatusList = dataDictionaryService.getDataDictionaryList("APP_STATUS");

        model.addAttribute("appInfoList", appInfoList);
        model.addAttribute("pages", pageSupport);
        model.addAttribute("querySoftwareName", softwarename);
        model.addAttribute("queryCategoryLevel1", categoryLevel1);
        model.addAttribute("queryCategoryLevel2", categoryLevel2);
        model.addAttribute("queryCategoryLevel3", categoryLevel3);
        model.addAttribute("queryFlatformId", flatFormId);
        model.addAttribute("categoryLevel1List", categoryList1);
        model.addAttribute("flatFormList", flatFormList);
        model.addAttribute("statusList", appStatusList);
        model.addAttribute("queryStatus", status);

        //二级分类列表和三级分类列表---回显
        if (categoryLevel2 != null) {
            List<AppCategory> queryCategoryLevel2 = appCategoryService.getByCategorynameAppCategoryList(categoryLevel1);
            model.addAttribute("categoryLevel2List", queryCategoryLevel2);
        }
        if (categoryLevel3 != null) {
            List<AppCategory> queryCategoryLevel3 = appCategoryService.getByCategorynameAppCategoryList(categoryLevel2);
            model.addAttribute("categoryLevel3List", queryCategoryLevel3);
        }
        return "/developer/appinfolist";
    }
    /**
     * 三级分类查询
     * @param pid
     * @return
     */
    @GetMapping("/categorylevellist.json")
    @ResponseBody
    @CrossOrigin
    public List<AppCategory> getByCategorynameAppCategoryList(@RequestParam(defaultValue = "1" ,name = "pid") Integer pid){
        return appCategoryService.getByCategorynameAppCategoryList(pid);
    }
    //</editor-fold>


    //<editor-fold desc="app添加">
    /**
     *app信息添加跳转
     * @return
     */
    @RequestMapping("/appinfoadd")
    public  String appInfoAdd(){
     return  "developer/appinfoadd";
    }
    /**
     * apk名称检查
     * @param APKName
     * @return
     */
    @RequestMapping("/apkexist.json")
    @ResponseBody
    public  Object apkexist(@RequestParam String APKName){
        HashMap<String,String> resultMap = new HashMap<String, String>();
        if (StringUtils.isNullOrEmpty(APKName)){
            resultMap.put("APKName","empty");
        }else {
            AppInfo appInfo = null;
            try {
                appInfo = appInfoService.getAppInfo(null,APKName);
            }catch (Exception e){
                e.printStackTrace();
            }
            if (null != appInfo){
                resultMap.put("APKName","exist");
            }else {
                resultMap.put("APKName","noexist");
            }
        }
        return JSONArray.toJSONString(resultMap);
    }


    //ajax获取平台列表
    @ResponseBody
    @RequestMapping("/datadictionarylist.json")
    public Object getFlatList(@RequestParam("tcode") String typeCode) {
        //获取平台列表
        List<DataDictionary> flatFormList = dataDictionaryService.getDataDictionaryList(typeCode);
        return flatFormList;
    }
    /**
     * 保存新增appInfo的数据
     * @param appInfo
     * @param session
     * @param request
     * @param attach
     * @return
     */
    @RequestMapping( "/appinfoaddsave")
    public String addSave(AppInfo appInfo,
                          HttpSession session, HttpServletRequest request,
                          @RequestParam(value = "a_logoPicPath",required = false) MultipartFile attach){

        String logoPicPath = null;
        String logoLocPath = null;
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
            String oldFileName = attach.getOriginalFilename();//原文件名
            String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
            int filesize = 5000000;
            if (attach.getSize() > filesize) {//上传大小不得超过 5M
                request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_4);
                return "developer/appinfoadd";
            } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jepg") || prefix.equalsIgnoreCase("pneg")) {//上传图片格式
                String fileName = appInfo.getApkname() + ".jpg";//上传LOGO图片命名:apk名称.jpg
                File targetFile = new File(path, fileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_2);
                    return "developer/appinfoadd";
                }
                logoPicPath = request.getContextPath() + "/statics/uploadfiles/" + fileName;
                logoLocPath = path + File.separator + fileName;
            } else {
                request.setAttribute("fileUploadError", Constants.FILEUPLOAD_ERROR_3);
                return "developer/appinfoadd";
            }
        }

        appInfo.setCreatedby(((DevUser) session.getAttribute(Constants.DEV_USER_SESSION)).getId());
        appInfo.setCreationdate(new Date());
        appInfo.setLogopicpath(logoPicPath);
        appInfo.setLogolocpath(logoLocPath);
        appInfo.setDevid(((DevUser) session.getAttribute(Constants.DEV_USER_SESSION)).getId());
        appInfo.setStatus(Long.valueOf(1));

        try {
            if (appInfoService.add(appInfo)){
                return "redirect:/manager/dev/list";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        request.setAttribute("fileUploadError","上传失败SASAS");
        return "developer/appinfoadd";
    }
    //</editor-fold>


    //<editor-fold desc="查看详情">
    //查看app和版本信息
    @RequestMapping("/appview")
    public String getAppAndVersionById(@RequestParam("id") Integer id,
                                       Model model) {
        AppInfo appInfo = appInfoService.getAppInfoById(id);
        List<AppVersion> appVersionList = appVersionService.getAppVersionByvId(id);
        model.addAttribute("appInfo", appInfo);
        model.addAttribute("appVersionList", appVersionList);
        return "developer/appinfoview";
    }
    //</editor-fold>

    //<editor-fold desc="app修改">
    //修改回显数据
    @RequestMapping("/toAppInfoModify")
    public String toAppInfoModify(@RequestParam("id") Integer id,
                                  Model model) {
        AppInfo appInfo = appInfoService.getAppInfoById(id);
        model.addAttribute("appInfo", appInfo);
        return "developer/appinfomodify";
    }

    //修改appInfo数据
    @PostMapping("/appInfoModify")
    public String appInfoModify(AppInfo appInfo,
                                HttpSession session,
                                HttpServletRequest request,
                                @RequestParam(value = "attach", required = false) MultipartFile attach) {
        String logoPicPath = null;
        String logoLocPath = null;
        System.out.println(appInfo.getFlatformid());
        String APKName = appInfo.getApkname();
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
            String oldFileName = attach.getOriginalFilename();//原文件名
            String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
            int filesize = 500000;
            if (attach.getSize() > filesize) {//上传大小不得超过 50k
                return "redirect:/manager/dev/toAppInfoModify?id=" + appInfo.getId();
            } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jepg") || prefix.equalsIgnoreCase("pneg")) {//上传图片格式
                String fileName = APKName + ".jpg";//上传LOGO图片命名:apk名称.apk
                File targetFile = new File(path, fileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return "redirect:/manager/dev/toAppInfoModify?id=" + appInfo.getId();
                }
                logoPicPath = request.getContextPath() + "/statics/uploadfiles/" + fileName;
                logoLocPath = path + File.separator + fileName;
            } else {
                return "redirect:/manager/dev/toAppInfoModify?id=" + appInfo.getId();
            }
        }
        appInfo.setModifyby(((DevUser) session.getAttribute(Constants.DEV_USER_SESSION)).getId());
        appInfo.setModifydate(new Date());
        appInfo.setLogolocpath(logoLocPath);
        appInfo.setLogopicpath(logoPicPath);
        try {
            if (appInfoService.updateApp(appInfo) > 0) {
                return "redirect:/manager/dev/list";
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return "developer/appinfomodify";
    }
    //</editor-fold>

    //<editor-fold desc="删除模块">
    @RequestMapping("/delapp.json")
    @ResponseBody
    public Object delAppInfo(@RequestParam("id") Integer id){
        HashMap<String,Object> hashMap =new HashMap<>();
        if(id==null){
            hashMap.put("delResult","notexist");
        }else {
           Integer result= appInfoService.deleteAppInfById(id);
           if(result>0){
               hashMap.put("delResult","true");
           }else {
               hashMap.put("delResult","false");
           }
        }
        return hashMap;

    }
    //</editor-fold>

    //<editor-fold desc="商品上架下架功能">
    @RequestMapping("/sale.json")
    @ResponseBody
    public Object onOrOffSale(@RequestParam("appId") Integer appId, HttpSession session) {
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        System.out.println("aaaaaaaaaaaaaaaaaaaaaa"+appId);
        //保存数据
        if (appId != null) {
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa");
            resultMap.put("errorCode", "0");
            resultMap.put("appId", appId);
        }
        if (appId > 0) {


            try {
                //获取开发者信息
                DevUser devUser = (DevUser) session.getAttribute(Constants.DEV_USER_SESSION);
                AppInfo appInfo = new AppInfo();
                //传递appid和被修改人的id
                appInfo.setId(Long.valueOf(appId));
                appInfo.setModifyby(devUser.getId());
                //修改
                if (appInfoService.appsysUpdateSaleStatusByAppId(appInfo)) {
                    resultMap.put("resultMsg", "success");
                } else {
                    resultMap.put("resultMsg", "failed");
                }


            } catch (Exception e) {
                e.printStackTrace();
                resultMap.put("errorCode", "exception000001");
            }
        } else {
            //errorCode:0为正常
            resultMap.put("errorCode", "param000001");
        }

        return resultMap;
    }
    //</editor-fold>


    //<editor-fold desc="新增版本">
    @RequestMapping("/appversionadd")
    public String appversionadd(@RequestParam("id") Integer id,HttpServletRequest request){
        List<AppVersion> appVersionList=appVersionService.getAppVersionList(id);
        request.setAttribute("appId",id);
        return "developer/appversionadd";
    }

    @RequestMapping("/addversionsave")
    public String addversionsave(HttpSession session,HttpServletRequest request,
                                 AppVersion appVersion
                             ,@RequestParam(value = "a_downloadLink",required = false) MultipartFile a_downloadLink    ) {
        try {
            appVersion.setApklocpath(OssUtil.upload(a_downloadLink.getOriginalFilename(),a_downloadLink.getInputStream()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        appVersion.setCreatedby(((DevUser) session.getAttribute(Constants.DEV_USER_SESSION)).getId());
        appVersion.setCreationdate(new Date());
        String appId = request.getParameter("appId");
        appVersion.setAppid(Long.valueOf(appId));


        Integer result = appVersionService.insertVersion(appVersion);//插入新版本

        Integer vsersionid= appVersionService.selectNewVersionidByAppid(Integer.valueOf(appId));
        System.out.println("111111111111111111111111"+vsersionid);
        AppInfo appInfo;
        appInfo=appInfoService.getAppInfoById(Integer.valueOf(appId));
        appInfo.setVersionid(Long.valueOf(vsersionid));
        appInfoService.updateApp(appInfo);


        if(result>0){
            return "redirect:/manager/dev/list";
        }else {
            List<AppVersion> appVersionList=appVersionService.getAppVersionList(Integer.parseInt(String.valueOf(appVersion.getAppid())));
            request.setAttribute("fileUploadError","添加失败");
            return "developer/appversionadd";
        }


    }
    //</editor-fold>


    @RequestMapping("/appversionmodify")
    public String appversionmodify(@RequestParam("vid") Integer versionid, @RequestParam("aid") Integer appinfoid,HttpSession session){
        List<AppVersion> appVersionList = appVersionService.getAppVersionList(appinfoid);
        AppVersion appVersion = appVersionService.selectNewVersion(appinfoid);
        session.setAttribute("appVersionList",appVersionList);
        session.setAttribute("appVersion",appVersion);
        return "developer/appversionmodify";
    }

    @RequestMapping("/appversionmodifysave")
    public String appversionmodifysave(AppVersion appVersion,HttpServletRequest request,HttpSession session){
        String id = request.getParameter("id");//版本id
        appVersion=appVersionService.getById(Integer.valueOf(id));
        String appId = request.getParameter("appId");


        String versionSizeStr = request.getParameter("versionSize");
        // 假设 versionSize 应该是 BigDecimal 类型
        if (versionSizeStr != null && !versionSizeStr.isEmpty()) {
            try {
                BigDecimal versionSize = new BigDecimal(versionSizeStr);
                appVersion.setVersionsize(versionSize);
            } catch (NumberFormatException e) {
               e.printStackTrace();
            }
        }
        appVersion.setVersioninfo(request.getParameter("versionInfo"));
        //设置更新者

        DevUser devUser  =(DevUser) session.getAttribute(Constants.DEV_USER_SESSION);
        appVersion.setModifyby(devUser.getId());
        appVersion.setModifydate(new Date());
        boolean update = appVersionService.updateNewVersion(appVersion);
        if(update){
            return "redirect:/manager/dev/list";
        }
        return "redirect:/manager/dev/list";
    }



}
